﻿#include "openglwidget.h"
#include <QOpenGLShader>
#include <QFile>
#include <QTextStream>
#include <QDebug>

OpenGLWidget::OpenGLWidget(QWidget *parent)
    : QOpenGLWidget(parent)
    , program(nullptr)
    , vbo(0)
    , vao(0) 
{

}

OpenGLWidget::~OpenGLWidget() 
{
    makeCurrent();
    delete program;
    
    glDeleteBuffers(1, &vbo);
    glDeleteVertexArrays(1, &vao);
    
    doneCurrent();
}

QString readShaderFile(const QString &path) {
    QFile file(path);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "Could not open shader file:" << path;
        return QString();
    }

    QTextStream in(&file);
    return in.readAll();
}

void OpenGLWidget::initializeGL() {
    makeCurrent();

    initializeOpenGLFunctions();

   std::printf("%s \n", glGetString(GL_VERSION));
   std::printf("%s \n", glGetString(GL_SHADING_LANGUAGE_VERSION));

    QString vertexShaderSource = readShaderFile(":/shaders/vertex_shader.glsl");
    QString fragmentShaderSource = readShaderFile(":/shaders/fragment_shader.glsl");

    program = new QOpenGLShaderProgram();
    if (!program->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSource)) {
        qDebug() << "Vertex Shader Error:" << program->log();
    }
    if (!program->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSource)) {
        qDebug() << "Fragment Shader Error:" << program->log();
    }
    if (!program->link()) {
        qDebug() << "Shader Program Link Error:" << program->log();
    }
  

    GLfloat vertices[] = {
        -0.5f, -0.5f, 0.5f,
         0.5f, -0.5f, 0.5f,
         0.5f,  0.5f, 0.5f,

         0.5f,  0.5f, 0.5f,
         -0.5f, -0.5f, 0.5f,
         -0.5f, 0.5f, 0.5f,
    };


    
    glGenVertexArrays(1, &vao);
    glGenBuffers(1, &vbo);

    glBindVertexArray(vao);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (void*)0);
    glEnableVertexAttribArray(0);
    
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);

    
}

void OpenGLWidget::resizeGL(int w, int h) {
    makeCurrent();
    
    glViewport(0, 0, w, h);
}

void OpenGLWidget::paintGL() {
    makeCurrent();
    

    glClearColor(1.0f, 1.0f, 0.0f, 1.0f); // Set background color
    glClear(GL_COLOR_BUFFER_BIT);

    program->bind();
    glBindVertexArray(vao);
    glDrawArrays(GL_TRIANGLES, 0, 6);
    glBindVertexArray(0);
    program->release();
}
